package com.bayair.doctor.net;

import android.text.TextUtils;
import android.util.Log;

import java.util.Map;
import java.util.WeakHashMap;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.functions.ObjectHelper;

/**
 *  管理rxjava的发布事件订阅、取消
 *      销毁时：
 *      DisposableManager.ins().dispose(toString());
 */
public class DisposableManager {

    public static DisposableManager ins() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final DisposableManager INSTANCE = new DisposableManager();
    }

    private final Map<String, CompositeDisposable> mDispose = new WeakHashMap<>();

    private DisposableManager() {
    }

    public void onSubscribe(String presenter, Disposable disposable) {
        ObjectHelper.requireNonNull(disposable, "DisposableManager-onSubscribe() disposable is NULL!");
        if (TextUtils.isEmpty(presenter)) {
            Log.e("==DisposableManager==","DisposableManager-onSubscribe() presenter is NULL!");
        }
        disposables(presenter).add(disposable);
    }

    public void onError(String presenter, Disposable disposable) {
        ObjectHelper.requireNonNull(disposable, "DisposableManager-onError() disposable is NULL!");
        disposables(presenter).remove(disposable);
    }

    public void onComplete(String presenter, Disposable disposable) {
        ObjectHelper.requireNonNull(disposable, "DisposableManager-onComplete() disposable is NULL!");
        disposables(presenter).remove(disposable);
    }

    public void dispose(String presenter) {
        CompositeDisposable remove = mDispose.remove(presenter);
        if (remove == null) {
            return;
        }
        remove.dispose();
    }

    private CompositeDisposable disposables(String presenter) {
        CompositeDisposable disposables = mDispose.get(presenter);
        if (disposables == null) {
            disposables = new CompositeDisposable();
            mDispose.put(presenter, disposables);
        }
        return disposables;
    }
}
